import pytest
from django.test import TestCase

from .models import A, C, D, E


class ViewsTest(TestCase):
    def test_ip(self):
        resp = self.client.get("/ip/")
        assert resp.content == b"127.0.0.1"
        resp = self.client.get("/ip/", HTTP_X_FORWARDED_FOR="10.0.0.1")
        assert resp.content == b"10.0.0.1"

    def test_agent(self):
        resp = self.client.get("/agent/")
        assert resp.content == b"unknown"
        WECHAT = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.4(0x17000428) NetType/WIFI Language/zh_CN"  # NOQA
        ALIPAY = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16G114 NebulaSDK/1.8.100112 Nebula WK PSDType(1) AlipayDefined(nt:WIFI,ws:375|603|2.0) AliApp(AP/10.1.80.6060) AlipayClient/10.1.80.6060 Language/zh-Hans Region/CN"  # NOQA
        QQ = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 QQ/8.0.0.472 V1_IPH_SQ_8.0.0_1_APP_A Pixel/750 Core/WKWebView Device/Apple(iPhone 6) NetType/WIFI QBWebViewType/1 WKType/1"  # NOQA
        resp = self.client.get("/agent/", HTTP_USER_AGENT=WECHAT)
        assert resp.content == b"wechat"
        resp = self.client.get("/agent/", HTTP_USER_AGENT=ALIPAY)
        assert resp.content == b"alipay"
        resp = self.client.get("/agent/", HTTP_USER_AGENT=QQ)
        assert resp.content == b"wechat"

    def test_url(self):
        resp = self.client.get("/url/xxx/")
        assert resp.content == b"http://testserver/url/xxx/"

    def test_etag(self):
        resp = self.client.get("/etag/")
        assert resp.status_code == 200



@pytest.mark.django_db(transaction=True)
def test_model():
    # test ChoicesField
    obj = A.objects.create(a="0", b="00")
    assert obj.get_a_display() == "a"
    assert obj.b == "00"

    # test WeakForeignKey
    obj2 = C.objects.create(a=obj)
    assert obj2 in obj.c_set.all()
    obj2_1 = C.objects.create()
    assert obj2_1.a is None

    # test CascadeForeignKey
    obj3 = D.objects.create(a=obj)
    assert obj3 in obj.d_set.all()
    try:
        D.objects.create()
    except Exception as e:
        err = str(e)
        assert "NOT NULL constraint" in err or "not-null constraint" in err

    # test AttrDictMixin
    obj4 = E.objects.create(foo={"a": 1, "bc": 2})
    obj5 = E.objects.get(pk=obj4.pk)
    assert obj4.foo.a == obj4.foo["a"]
    assert obj5.foo.a == obj4.foo["a"]
